<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="java,数据结构">
    <meta name="description" content="C# | Web | html | python |">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-c9IEbSDR1U" />

	
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>二叉树 | X-Y-Z`s Blog</title>
	
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
<meta name="generator" content="Hexo 5.4.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>



   <style>
    body{
       background-image: url(/medias/background.JPG);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body  onload="opener.location.reload()">

	
    <header class="navbar-fixed">

<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?b3593488200a34a873defcaa11fc888a";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">X-Y-Z`s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-sitemap" style="zoom: 0.6;"></i>
      
      <span>归类</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>归档</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/navigate" class="waves-effect waves-light">
      
      <i class="fas fa-location-arrow" style="zoom: 0.6;"></i>
      
      <span>导航</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">X-Y-Z`s Blog</div>
        <div class="logo-desc">
            
            C# | Web | html | python |
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-sitemap"></i>
			
			归类
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/categories " style="margin-left:50px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:28px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:50px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:28px" ></i>
			      
		          <span>归档</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/navigate" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-location-arrow"></i>
			
			Navigate
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork He
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #4e9ef5;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork He" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/12.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">二叉树</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

	.toc-widget.card.toc-fixed {
    opacity: 0.85;
	}
    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
		height: 500px;
		overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }
    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">
                                <span class="chip bg-color">数据结构</span>
                            </a>
                        
                            <a href="/tags/%E6%A0%91/">
                                <span class="chip bg-color">树</span>
                            </a>
                        
                            <a href="/tags/Tree/">
                                <span class="chip bg-color">Tree</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/java/" class="post-category">
                                java
                            </a>
                        
                            <a href="/categories/java/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" class="post-category">
                                数据结构
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2022-02-10
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2022-08-29
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    22 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="0-先说下"><a href="#0-先说下" class="headerlink" title="0. 先说下"></a>0. 先说下</h2><p>所有源码，是学习<code>java</code>的同时练习数据结构，所以有的地方可能并不高效，安全，考虑的不周全等。即小打小闹，不建议用于实际开发中。</p>
<p>如果发现问题，请赶紧联系作者进行修改。</p>
<blockquote>
<p><mark>注意：</mark></p>
<p>​        所有内容中较为复杂的是删除某一个节点，其他的比如遍历，深度，查找，基本属于同一操作。</p>
<p>除此之外的其他内容都是添枝加叶，不是重点。</p>
</blockquote>
<h2 id="1-树的基本操作"><a href="#1-树的基本操作" class="headerlink" title="1. 树的基本操作"></a>1. 树的基本操作</h2><ul>
<li> 初始化</li>
<li>添加节点</li>
<li>查找节点 (按值)</li>
<li>删除节点的子树</li>
<li>查看深度</li>
<li>遍历</li>
</ul>
<h2 id="2-源码"><a href="#2-源码" class="headerlink" title="2. 源码"></a>2. 源码</h2><h3 id="2-0-大体代码"><a href="#2-0-大体代码" class="headerlink" title="2.0  大体代码"></a>2.0  大体代码</h3><figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 日期：2022/1/30</span><br><span class="hljs-comment"> * 时间：2:15</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> xyz</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TreeByClass</span> </span>{<br>    <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 遍历方法枚举</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">traverseOrder</span> </span>{ }<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 树的节点</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> tr 树初始化，并添加数据。</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">initTree</span><span class="hljs-params">(Tree tr)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 从此节点开始计算深度。</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span>  father节点开始的深度</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">depthTree</span><span class="hljs-params">(Tree father)</span></span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    起始节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> treeNodes 一个object类型的列表，用于接收遍历数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> trOr      遍历方法，DLR，LDR，LRD</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">traverseTree</span><span class="hljs-params">(Tree father, List&lt;Object&gt; treeNodes, traverseOrder trOr)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 查找的值</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 返回值所在节点。如果不存在则返回最后null。</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">findNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> ele 插入的节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 插入到合适位置的数据</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertValue</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{}<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, Tree ele)</span> </span>{}<br>    <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点的子树（节点）</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{}<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTree</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{}<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params"><code class="language-hljs java"><span class="hljs-keyword">import</span> java.util.ArrayList;<br><span class="hljs-keyword">import</span> java.util.List;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 日期：2022/1/30</span><br><span class="hljs-comment"> * 时间：2:15</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> xyz</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TreeByClass</span> </span>{<br>    <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 遍历方法枚举</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">traverseOrder</span> </span>{ }<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 树的节点</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> tr 树初始化，并添加数据。</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">initTree</span><span class="hljs-params">(Tree tr)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 从此节点开始计算深度。</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span>  father节点开始的深度</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">depthTree</span><span class="hljs-params">(Tree father)</span></span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    起始节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> treeNodes 一个object类型的列表，用于接收遍历数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> trOr      遍历方法，DLR，LDR，LRD</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">traverseTree</span><span class="hljs-params">(Tree father, List&lt;Object&gt; treeNodes, traverseOrder trOr)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 查找的值</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 返回值所在节点。如果不存在则返回最后null。</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">findNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{}<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> ele 插入的节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 插入到合适位置的数据</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertValue</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{}<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, Tree ele)</span> </span>{}<br>    <br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点的子树（节点）</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{}<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTree</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{}<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{}<br>}<br></code></pre></td></tr></tbody></table></figure>



<h3 id="2-1-main函数"><a href="#2-1-main函数" class="headerlink" title="2.1 main函数"></a>2.1 <code>main</code>函数</h3><p>过程：</p>
<pre class="mermaid"></pre>
<p>初始化-&gt;遍历存入-&gt;删除 <code>(1+10*n,n∈[1,9])</code> -&gt;删除树-&gt;遍历存入-&gt;输出初始列表-&gt;输出最终列表-&gt;生成删除节点列表-&gt;输出删除的节点列表</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>{<br>    Tree oneTree = initTree();<br>    <span class="hljs-comment">//用来保存开始与最后树节点们,以及删除的节点们。</span><br>    List&lt;Object&gt; nodeData1 = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    List&lt;Object&gt; nodeData2 = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>	List&lt;Object&gt; deleteNode= <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    <span class="hljs-comment">//遍历数据</span><br>    traverseTree(oneTree, nodeData1, traverseOrder.LDR);<br><br>    <span class="hljs-comment">//删除1~91。</span><br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">100</span>; i += <span class="hljs-number">10</span>) {<br>        deleteNode(oneTree, i);<br>    }<br>    <span class="hljs-comment">//再删除个子树。</span><br>    deleteTree(oneTree, <span class="hljs-number">55</span>);<br>    <span class="hljs-comment">//遍历修改过后的树</span><br>    traverseTree(oneTree, nodeData2, traverseOrder.LDR);<br>    Object[] arr2 = nodeData2.toArray();<br>    System.out.print(<span class="hljs-string">"\n最初的数组： "</span>);<br>    <span class="hljs-keyword">for</span> (Object o : nodeData1) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string">"%3d,"</span>, o));<br>    }<br>    System.out.print(<span class="hljs-string">"\n删除后数组： "</span>);<br>    <span class="hljs-keyword">for</span> (Object o : nodeData2) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string">"%3d,"</span>, o));<br>    }<br>    System.out.println();<br>    System.out.print(<span class="hljs-string">"删除数组： "</span>);<br>    deleteNode= nodeData1.stream().filter(elem -&gt; !nodeData2.contains(elem)).collect(Collectors.toList());<br>    <span class="hljs-keyword">for</span> (Object o : deleteNode) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string"><code class="language-hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>{<br>    Tree oneTree = initTree();<br>    <span class="hljs-comment">//用来保存开始与最后树节点们,以及删除的节点们。</span><br>    List&lt;Object&gt; nodeData1 = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    List&lt;Object&gt; nodeData2 = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>	List&lt;Object&gt; deleteNode= <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    <span class="hljs-comment">//遍历数据</span><br>    traverseTree(oneTree, nodeData1, traverseOrder.LDR);<br><br>    <span class="hljs-comment">//删除1~91。</span><br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">100</span>; i += <span class="hljs-number">10</span>) {<br>        deleteNode(oneTree, i);<br>    }<br>    <span class="hljs-comment">//再删除个子树。</span><br>    deleteTree(oneTree, <span class="hljs-number">55</span>);<br>    <span class="hljs-comment">//遍历修改过后的树</span><br>    traverseTree(oneTree, nodeData2, traverseOrder.LDR);<br>    Object[] arr2 = nodeData2.toArray();<br>    System.out.print(<span class="hljs-string">"\n最初的数组： "</span>);<br>    <span class="hljs-keyword">for</span> (Object o : nodeData1) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string">"%3d,"</span>, o));<br>    }<br>    System.out.print(<span class="hljs-string">"\n删除后数组： "</span>);<br>    <span class="hljs-keyword">for</span> (Object o : nodeData2) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string">"%3d,"</span>, o));<br>    }<br>    System.out.println();<br>    System.out.print(<span class="hljs-string">"删除数组： "</span>);<br>    deleteNode= nodeData1.stream().filter(elem -&gt; !nodeData2.contains(elem)).collect(Collectors.toList());<br>    <span class="hljs-keyword">for</span> (Object o : deleteNode) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(String.format(<span class="hljs-string">"%3d,"</span>, o));<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>



<h3 id="2-2-方法部分"><a href="#2-2-方法部分" class="headerlink" title="2.2 方法部分"></a>2.2 方法部分</h3><p>如下几部分:</p>
<ul>
<li><p>遍历顺序枚举</p>
</li>
<li><p>节点类</p>
</li>
<li><p>初始化</p>
</li>
<li><p>深度</p>
</li>
<li><p>遍历</p>
</li>
<li><p>查找节点</p>
</li>
<li><p>插入</p>
<ul>
<li>插入值</li>
<li>插入节点</li>
</ul>
</li>
<li><p>删除</p>
<ul>
<li>删除节点</li>
<li>删除子树</li>
</ul>
</li>
</ul>
<h4 id="2-2-1-枚举"><a href="#2-2-1-枚举" class="headerlink" title="2.2.1 枚举"></a>2.2.1 枚举</h4><p>没的说。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">traverseOrder</span> </span>{<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 先序遍历</span><br><span class="hljs-comment">    */</span><br>    DLR,<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 中序遍历</span><br><span class="hljs-comment">    */</span><br>    LDR,<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 后序遍历</span><br><span class="hljs-comment"><code class="language-hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">traverseOrder</span> </span>{<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 先序遍历</span><br><span class="hljs-comment">    */</span><br>    DLR,<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 中序遍历</span><br><span class="hljs-comment">    */</span><br>    LDR,<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 后序遍历</span><br><span class="hljs-comment">    */</span><br>    LRD<br>}<br></code></pre></td></tr></tbody></table></figure>



<h4 id="2-2-2-节点类"><a href="#2-2-2-节点类" class="headerlink" title="2.2.2 节点类"></a>2.2.2 节点类</h4><p>节点的类。</p>
<p>包含：四个属性（左枝，右枝，父节点，数据），</p>
<p>一个构造参数（需要导入数据）。</p>
<blockquote>
<p>data属性可修改为其他类型，比如类。</p>
<p>如果修改，记得修改主函数中的列表等地的类型。</p>
</blockquote>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> </span>{<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">         * L D R 树</span><br><span class="hljs-comment">         */</span><br>    Tree left;<br>    Tree right;<br>    Tree parNode;<br>    <span class="hljs-keyword">int</span> data;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Tree</span><span class="hljs-params">(Tree parNode, <span class="hljs-keyword">int</span> data)</span> </span>{<br>        <span class="hljs-keyword">this</span>.left = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">this</span>.right = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">this</span>.parNode = parNode;<br>        <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Tree</span> </span>{<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">         * L D R 树</span><br><span class="hljs-comment">         */</span><br>    Tree left;<br>    Tree right;<br>    Tree parNode;<br>    <span class="hljs-keyword">int</span> data;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Tree</span><span class="hljs-params">(Tree parNode, <span class="hljs-keyword">int</span> data)</span> </span>{<br>        <span class="hljs-keyword">this</span>.left = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">this</span>.right = <span class="hljs-keyword">null</span>;<br>        <span class="hljs-keyword">this</span>.parNode = parNode;<br>        <span class="hljs-keyword">this</span>.data = data;<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>



<h4 id="2-2-3-初始化"><a href="#2-2-3-初始化" class="headerlink" title="2.2.3 初始化"></a>2.2.3 初始化</h4><p>初始化树，添加30个随机的1~99的随机数。获取随机数的方法在下方。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> 返回创建并添加过数据的树</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">initTree</span><span class="hljs-params">()</span> </span>{<br>    Tree term = <span class="hljs-keyword">new</span> Tree(<span class="hljs-keyword">null</span>, randomInt());<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">30</span>;) {<br>        <span class="hljs-keyword">int</span> tInt = randomInt();<br>        <span class="hljs-keyword">if</span> (findNode(term, tInt) == <span class="hljs-keyword">null</span>) {<br>            insertNode(term, tInt);<br>            i++;<br>        }<br>    }<br>    <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> 返回创建并添加过数据的树</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">initTree</span><span class="hljs-params">()</span> </span>{<br>    Tree term = <span class="hljs-keyword">new</span> Tree(<span class="hljs-keyword">null</span>, randomInt());<br>    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">30</span>;) {<br>        <span class="hljs-keyword">int</span> tInt = randomInt();<br>        <span class="hljs-keyword">if</span> (findNode(term, tInt) == <span class="hljs-keyword">null</span>) {<br>            insertNode(term, tInt);<br>            i++;<br>        }<br>    }<br>    <span class="hljs-keyword">return</span> term;<br>}<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p><code>randomInt</code> 函数</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java">&gt;<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">randomInt</span><span class="hljs-params">()</span> </span>{<br>   <span class="hljs-keyword">return</span> Math.round((<span class="hljs-keyword">float</span>) Math.random() * <span class="hljs-number"><code class="language-hljs java">&gt;<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">randomInt</span><span class="hljs-params">()</span> </span>{<br>   <span class="hljs-keyword">return</span> Math.round((<span class="hljs-keyword">float</span>) Math.random() * <span class="hljs-number">100</span>);<br>>}<br></code></pre></td></tr></tbody></table></figure>

<p>获取一个随机数 1~99，</p>
</blockquote>
<h4 id="2-2-4-树深度"><a href="#2-2-4-树深度" class="headerlink" title="2.2.4 树深度"></a>2.2.4 树深度</h4><p>返回一个树的深度，与遍历极为类似，稍微改点东西。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 从此节点开始计算深度。</span><br><span class="hljs-comment">* <span class="hljs-doctag">@return</span>  father节点开始的深度</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">depthTree</span><span class="hljs-params">(Tree father)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.right == <span class="hljs-keyword">null</span> &amp;&amp; father.left == <span class="hljs-keyword">null</span>) {<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword">int</span> left = <span class="hljs-number">1</span>, right = <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>            left += depthTree(father.left);<br>            <span class="hljs-comment">//本层加上子树的最大层</span><br>        }<br>        <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>            right += depthTree(father.right);<br>            <span class="hljs-comment">//本层加子树的最大层</span><br>        }<br>        <span class="hljs-keyword">return</span> Math.max(right, left);<br>        <span class="hljs-comment"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 从此节点开始计算深度。</span><br><span class="hljs-comment">* <span class="hljs-doctag">@return</span>  father节点开始的深度</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">depthTree</span><span class="hljs-params">(Tree father)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.right == <span class="hljs-keyword">null</span> &amp;&amp; father.left == <span class="hljs-keyword">null</span>) {<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword">int</span> left = <span class="hljs-number">1</span>, right = <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>            left += depthTree(father.left);<br>            <span class="hljs-comment">//本层加上子树的最大层</span><br>        }<br>        <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>            right += depthTree(father.right);<br>            <span class="hljs-comment">//本层加子树的最大层</span><br>        }<br>        <span class="hljs-keyword">return</span> Math.max(right, left);<br>        <span class="hljs-comment">//返回左右树中的极大值，如果相等，则返回右值（右值也是一，表示当前层）</span><br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>

<blockquote>
<p>节点数统计方法类似，此处偷个懒。</p>
</blockquote>
<h4 id="2-2-5-遍历树"><a href="#2-2-5-遍历树" class="headerlink" title="2.2.5 遍历树"></a>2.2.5 遍历树</h4><p>三种方式，先序、中序、后序，这里通过一个枚举类型进行选择。</p>
<blockquote>
<p><code>LDR</code>:  从小到大顺序；</p>
<p>另外两种比较好观察数据树的结构。</p>
</blockquote>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    起始节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> treeNodes 一个object类型的列表，用于接收遍历数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> trOr      遍历方法，DLR，LDR，LRD </span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">traverseTree</span><span class="hljs-params">(Tree father, List&lt;Object&gt; treeNodes, traverseOrder trOr)</span> </span>{<br>    <span class="hljs-keyword">switch</span> (trOr) {<br>        <span class="hljs-keyword">case</span> DLR: {<br>            <span class="hljs-comment">//前序遍历</span><br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">case</span> LDR: {<br>            <span class="hljs-comment">//中序遍历</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">case</span> LRD: {<br>            <span class="hljs-comment">//后序遍历</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">default</span>: {<br>            <span class="hljs-comment">//实际运行不到这里。</span><br>            System.out.println(<span class="hljs-string">"遍历方向有误，将默认采用中序遍历"</span>);<br>            traverseTree(father, treeNodes, traverseOrder.LDR);<br>            <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father    起始节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> treeNodes 一个object类型的列表，用于接收遍历数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> trOr      遍历方法，DLR，LDR，LRD </span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">traverseTree</span><span class="hljs-params">(Tree father, List&lt;Object&gt; treeNodes, traverseOrder trOr)</span> </span>{<br>    <span class="hljs-keyword">switch</span> (trOr) {<br>        <span class="hljs-keyword">case</span> DLR: {<br>            <span class="hljs-comment">//前序遍历</span><br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">case</span> LDR: {<br>            <span class="hljs-comment">//中序遍历</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">case</span> LRD: {<br>            <span class="hljs-comment">//后序遍历</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.left, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                traverseTree(father.right, treeNodes, trOr);<br>            }<br>            <span class="hljs-keyword">if</span> (father.data != -<span class="hljs-number">1</span>) {<br>                treeNodes.add(father.data);<br>            }<br>            <span class="hljs-keyword">break</span>;<br>        }<br>        <span class="hljs-keyword">default</span>: {<br>            <span class="hljs-comment">//实际运行不到这里。</span><br>            System.out.println(<span class="hljs-string">"遍历方向有误，将默认采用中序遍历"</span>);<br>            traverseTree(father, treeNodes, traverseOrder.LDR);<br>            <span class="hljs-keyword">break</span>;<br>        }<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>



<h4 id="2-2-6-查找节点"><a href="#2-2-6-查找节点" class="headerlink" title="2.2.6 查找节点"></a>2.2.6 查找节点</h4><p>通过遍历，再根据二叉树的特性，值小向左，值大向右。</p>
<p>找到时返回节点。</p>
<p>为了方便对节点的父节点进行操作，为节点设置了父节点属性。</p>
<blockquote>
<p>使用比较多，原理也比较简单。</p>
</blockquote>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> father    根节点</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> nodeValue 查找的值</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> 返回值所在节点。如果不存在则返回最后null。</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">findNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.data == nodeValue) {<br>        <span class="hljs-keyword">return</span> father;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword">while</span> (father.left != <span class="hljs-keyword">null</span> || father.right != <span class="hljs-keyword">null</span>) {<br>            <span class="hljs-keyword">if</span> (nodeValue &lt; father.data &amp;&amp; father.left != <span class="hljs-keyword">null</span>) {<br>                father = father.left;<br>            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (nodeValue &gt; father.data &amp;&amp; father.right != <span class="hljs-keyword">null</span>) {<br>                father = father.right;<br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-keyword">break</span>;<br>            }<br>        }<br>    }<br>    <span class="hljs-keyword">if</span> (father.data != nodeValue) {<br>        <span class="hljs-comment">//到底了没找到。</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> father    根节点</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> nodeValue 查找的值</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> 返回值所在节点。如果不存在则返回最后null。</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Tree <span class="hljs-title">findNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.data == nodeValue) {<br>        <span class="hljs-keyword">return</span> father;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword">while</span> (father.left != <span class="hljs-keyword">null</span> || father.right != <span class="hljs-keyword">null</span>) {<br>            <span class="hljs-keyword">if</span> (nodeValue &lt; father.data &amp;&amp; father.left != <span class="hljs-keyword">null</span>) {<br>                father = father.left;<br>            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (nodeValue &gt; father.data &amp;&amp; father.right != <span class="hljs-keyword">null</span>) {<br>                father = father.right;<br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-keyword">break</span>;<br>            }<br>        }<br>    }<br>    <span class="hljs-keyword">if</span> (father.data != nodeValue) {<br>        <span class="hljs-comment">//到底了没找到。</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-keyword">return</span> father;<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>



<h4 id="2-2-7-插入"><a href="#2-2-7-插入" class="headerlink" title="2.2.7 插入"></a>2.2.7 插入</h4><h5 id="2-2-7-1-插入值"><a href="#2-2-7-1-插入值" class="headerlink" title="2.2.7.1 插入值"></a>2.2.7.1 插入值</h5><p>根据值通过递归找到合适位置。然后新建节点，并连接。</p>
<p>此处的连接是双向的，因为存在父节点。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 插入到合适位置的数据</span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.data == -<span class="hljs-number">1</span>) {<br>        father.data = nodeValue;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非空树</span><br>        <span class="hljs-keyword">if</span> (father.data &gt; nodeValue) {<br>            <span class="hljs-comment">//左枝</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//存在节点继续</span><br>                insertNode(father.left, nodeValue);<br>            } <span class="hljs-keyword">else</span> {<br>                father.left = <span class="hljs-keyword">new</span> Tree(nodeValue);<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//右枝</span><br>            <span class="hljs-keyword">if</span> (father.data &lt; nodeValue) {<br>                <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//同理</span><br>                    insertNode(father.right, nodeValue);<br>                } <span class="hljs-keyword">else</span> {<br>                    father.right = <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> nodeValue 插入到合适位置的数据</span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> nodeValue)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.data == -<span class="hljs-number">1</span>) {<br>        father.data = nodeValue;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非空树</span><br>        <span class="hljs-keyword">if</span> (father.data &gt; nodeValue) {<br>            <span class="hljs-comment">//左枝</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//存在节点继续</span><br>                insertNode(father.left, nodeValue);<br>            } <span class="hljs-keyword">else</span> {<br>                father.left = <span class="hljs-keyword">new</span> Tree(nodeValue);<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//右枝</span><br>            <span class="hljs-keyword">if</span> (father.data &lt; nodeValue) {<br>                <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//同理</span><br>                    insertNode(father.right, nodeValue);<br>                } <span class="hljs-keyword">else</span> {<br>                    father.right = <span class="hljs-keyword">new</span> Tree(nodeValue);<br>                }<br>            }<br>        }<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>

<h5 id="2-2-7-2-插入节点"><a href="#2-2-7-2-插入节点" class="headerlink" title="2.2.7.2 插入节点"></a>2.2.7.2 插入节点</h5><p><code>public static void insertNode(Tree father, Tree ele) {}</code></p>
<p><code>father</code> 附加的目的树。</p>
<p><code>ele</code> 为一个树的根节点，即将一个树附加到另一个树的合适位置上。</p>
<p>主要操作为：</p>
<ol>
<li><p>判断是否为空树。</p>
<blockquote>
<p>   为空：</p>
<ol>
<li>将节点的数据赋值给目的节点。</li>
<li>修改附加节点的根节点的父节点（如果存在的话）。</li>
</ol>
</blockquote>
</li>
<li><p>通过递归根据子节点的值找到合适位置。</p>
</li>
<li><p>插入值。</p>
</li>
</ol>
<blockquote>
<p>在删除一个节点的方法中也有用到此方法。</p>
</blockquote>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> ele 插入节点</span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, Tree ele)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.parNode == <span class="hljs-keyword">null</span> &amp;&amp; father.data == -<span class="hljs-number">1</span>) {<br>        father.data = ele.data;<br>        father.left = ele.left;<br>        father.right = ele.right;<br>        ele.parNode = father;<br>        <span class="hljs-keyword">if</span> (ele.left != <span class="hljs-keyword">null</span>) {<br>            ele.left.parNode = father;<br>        }<br>        <span class="hljs-keyword">if</span> (ele.right != <span class="hljs-keyword">null</span>) {<br>            ele.right.parNode = father;<br>        }  <br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非空树</span><br>        <span class="hljs-keyword">if</span> (father.data &gt;= ele.data) {<br>            <span class="hljs-comment">//左枝</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//存在节点继续</span><br><br>                insertNode(father.left, ele);<br>            } <span class="hljs-keyword">else</span> {<br>                father.left = ele;<br>                ele.parNode = father;<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//右枝</span><br>            <span class="hljs-keyword">if</span> (father.data &lt; ele.data) {<br>                <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//同理</span><br>                    insertNode(father.right, ele);<br>                } <span class="hljs-keyword"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> father 根节点</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> ele 插入节点</span><br><span class="hljs-comment">     */</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">insertNode</span><span class="hljs-params">(Tree father, Tree ele)</span> </span>{<br>    <span class="hljs-keyword">if</span> (father.parNode == <span class="hljs-keyword">null</span> &amp;&amp; father.data == -<span class="hljs-number">1</span>) {<br>        father.data = ele.data;<br>        father.left = ele.left;<br>        father.right = ele.right;<br>        ele.parNode = father;<br>        <span class="hljs-keyword">if</span> (ele.left != <span class="hljs-keyword">null</span>) {<br>            ele.left.parNode = father;<br>        }<br>        <span class="hljs-keyword">if</span> (ele.right != <span class="hljs-keyword">null</span>) {<br>            ele.right.parNode = father;<br>        }  <br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非空树</span><br>        <span class="hljs-keyword">if</span> (father.data &gt;= ele.data) {<br>            <span class="hljs-comment">//左枝</span><br>            <span class="hljs-keyword">if</span> (father.left != <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//存在节点继续</span><br><br>                insertNode(father.left, ele);<br>            } <span class="hljs-keyword">else</span> {<br>                father.left = ele;<br>                ele.parNode = father;<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//右枝</span><br>            <span class="hljs-keyword">if</span> (father.data &lt; ele.data) {<br>                <span class="hljs-keyword">if</span> (father.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//同理</span><br>                    insertNode(father.right, ele);<br>                } <span class="hljs-keyword">else</span> {<br>                    father.right = ele;<br>                    ele.parNode = father;<br>                }<br>            }<br>        }<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>



<h4 id="2-2-8-删除"><a href="#2-2-8-删除" class="headerlink" title="2.2.8 删除"></a>2.2.8 删除</h4><h5 id="2-2-8-1-删除节点"><a href="#2-2-8-1-删除节点" class="headerlink" title="2.2.8.1 删除节点"></a>2.2.8.1 删除节点</h5><p>比较复杂的操作，难点在于考虑删除节点的上下情况。</p>
<p>如下为我的分类讨论（熟悉的名词）：</p>
<blockquote>
<p>先定义几个量：</p>
<p><code>deleteNode</code> :要删除的节点。</p>
<p><code>left</code> ：删除节点的左节点属性。</p>
<p><code>right</code>： 删除节点的右节点属性。</p>
<p><code>parNode</code>： 删除节点类的父节点属性。</p>
<p><code>parentOfNode</code>: 删除节点的父节点。</p>
</blockquote>
<p>① 叶节点。</p>
<p>② 非叶节点</p>
<ol>
<li><p>根节点</p>
<ol>
<li><p>左子树为空</p>
</li>
<li><p>右子树为空或两树都不为空。</p>
<blockquote>
<p>​        之所以把 仅右子树为空 与 两树都不为空 放一起，是因为有个操作可以简化过程。</p>
<p>​        原来过程分三种：</p>
<ul>
<li><p><code>deleteNode.left==null</code> ，<code>deleteNode.right!=null</code>。</p>
<p>操作：用<code>deleteNode.right</code> 的值覆盖<code>deleteNode</code></p>
</li>
<li><p><code>deleteNode.left!=null</code>，<code>deleteNode.right==null</code>。</p>
<p>操作：用<code>deleteNode.left</code> 的值覆盖<code>deleteNode</code></p>
</li>
<li><p><code>deleteNode.left!=null</code>，<code>deleteNode.right!=null</code>。</p>
<p>操作：用<code>deleteNode.left</code> 的值覆盖<code>deleteNode</code>，<mark style="color:yellow">然后将<code>deleteNode.right</code> 子树附加到<code>deleteNode.left</code>上</mark>，附加操作可使用<code>insertNode()</code></p>
<blockquote>
<p><code>deleteNode.left==null</code>且 <code>deleteNode.right==null</code> 为叶节点，最开始已排除。</p>
</blockquote>
</li>
</ul>
</blockquote>
</li>
</ol>
</li>
<li><p>非根节点</p>
<ol>
<li>…同上的分类，但是多一个操作，将父节点向下的连接进行修改（需要判断是左枝到<code>deleteNode</code>，还是右枝）</li>
</ol>
</li>
</ol>
<p>最后是一个输出此次删除操作消失的节点值，用于调试以及删除树操作的显示。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{<br>    <span class="hljs-comment">//未删除时根元素的全部元素</span><br>    List&lt;Object&gt; nodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    traverseTree(father, nodeData, traverseOrder.LDR);<br><br>    Tree term = findNode(father, value);<br>    <span class="hljs-keyword">if</span> (term == <span class="hljs-keyword">null</span>) {<br>        System.out.println(String.format(<span class="hljs-string">"未找到:%3d "</span>, value));<br>        <span class="hljs-keyword">return</span>;<br>    }<br>    <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span> &amp;&amp; term.right == <span class="hljs-keyword">null</span>) {<br>        <span class="hljs-comment">// 叶节点。 删除节点的左右节点都为空。</span><br>        term.left = <span class="hljs-keyword">null</span>;<br>        term.right = <span class="hljs-keyword">null</span>;<br>        term.data = -<span class="hljs-number">1</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非叶节点</span><br>        <span class="hljs-keyword">if</span> (term.parNode == <span class="hljs-keyword">null</span>) {<br>            <span class="hljs-comment">//删除根节点</span><br>            <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//左子树为空</span><br>                term.data = term.right.data;<br>                <span class="hljs-comment">//根节点的 左树的 左节点，左树的 右节点</span><br>                Tree rLOfTerm = term.right.left, rROfTerm = term.right.right;<br>                <span class="hljs-comment">//换子节点</span><br>                term.right = rROfTerm;<br>                term.left = rLOfTerm;<br>                <span class="hljs-comment">//换父节点</span><br>                <span class="hljs-keyword">if</span> (rLOfTerm != <span class="hljs-keyword">null</span>) {<br>                    rLOfTerm.parNode = term;<br>                }<br>                <span class="hljs-keyword">if</span> (rROfTerm != <span class="hljs-keyword">null</span>) {<br>                    rROfTerm.parNode = term;<br>                }           <br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-comment">//右子树为空,或两子树都在。</span><br>                <span class="hljs-comment">//根节点的 左树的 左节点，左树的 右节点</span><br>                Tree lLOfTerm = term.left.left, lROfTerm = term.left.right;<br>                <span class="hljs-comment">//换子节点</span><br>                term.data = term.left.data;<br>                term.left = lLOfTerm;<br>                Tree deleteNodeTermRight = term.right;<br>                term.right = lROfTerm;<br>                <span class="hljs-keyword">if</span> (deleteNodeTermRight != <span class="hljs-keyword">null</span>) {<br>                    insertNode(term, deleteNodeTermRight);<br>                }<br>                <span class="hljs-keyword">if</span> (lLOfTerm != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//左子树的左枝不为空。</span><br>                    lLOfTerm.parNode = term;<br>                }<br>                <span class="hljs-keyword">if</span> (lROfTerm != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//左子树的右枝不为空。</span><br>                    lROfTerm.parNode = term;<br>                }<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//删除非根节点。</span><br>            <span class="hljs-comment">//定位节点 父节点 左 右子树</span><br>            Tree parOfTerm = term.parNode, lNode = term.left, rNode = term.right;<br>            <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//删除节点左子树为空。</span><br>                <span class="hljs-comment">//换父节点</span><br>                rNode.parNode = parOfTerm;<br>                <span class="hljs-keyword">if</span> (parOfTerm.left == term) {<br>                    parOfTerm.left = rNode;<br>                } <span class="hljs-keyword">else</span> {<br>                    parOfTerm.right = rNode;<br>                }<br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-comment">//删除节点左子树为空，或两子树都在</span><br>                <span class="hljs-comment">//换父节点</span><br>                lNode.parNode = term.parNode;<br>                <span class="hljs-comment">//换子节点</span><br>                <span class="hljs-keyword">if</span> (parOfTerm.left == term) {<br>                    <span class="hljs-comment">//当前节点为父节点左枝，赋值</span><br>                    parOfTerm.left = lNode;<br>                } <span class="hljs-keyword">else</span> {<br>                    <span class="hljs-comment">//...</span><br>                    parOfTerm.right = lNode;<br>                }<br>                <span class="hljs-keyword">if</span> (term.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//将 右枝 根节点 插入到左枝中--子节点连带过去。</span><br>                    insertNode(term.left, term.right);<br>                }<br>            }<br>        }<br>    }<br><br>    System.out.println(String.format(<span class="hljs-string">"删除%3d,"</span>, value));<br>    <span class="hljs-comment">//删除后的所有元素</span><br>    List&lt;Object&gt; newNodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    traverseTree(father, newNodeData, traverseOrder.DLR);<br><br>    System.out.print(<span class="hljs-string">"\t删除元素: "</span>);<br>    <span class="hljs-comment">//原树的补集</span><br>    Object[] arr3 = nodeData.stream().filter(elem -&gt; !newNodeData.contains(elem)).toArray();<br>    <span class="hljs-keyword">for</span> (Object o : arr3) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(o + <span class="hljs-string"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteNode</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{<br>    <span class="hljs-comment">//未删除时根元素的全部元素</span><br>    List&lt;Object&gt; nodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    traverseTree(father, nodeData, traverseOrder.LDR);<br><br>    Tree term = findNode(father, value);<br>    <span class="hljs-keyword">if</span> (term == <span class="hljs-keyword">null</span>) {<br>        System.out.println(String.format(<span class="hljs-string">"未找到:%3d "</span>, value));<br>        <span class="hljs-keyword">return</span>;<br>    }<br>    <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span> &amp;&amp; term.right == <span class="hljs-keyword">null</span>) {<br>        <span class="hljs-comment">// 叶节点。 删除节点的左右节点都为空。</span><br>        term.left = <span class="hljs-keyword">null</span>;<br>        term.right = <span class="hljs-keyword">null</span>;<br>        term.data = -<span class="hljs-number">1</span>;<br>    } <span class="hljs-keyword">else</span> {<br>        <span class="hljs-comment">//非叶节点</span><br>        <span class="hljs-keyword">if</span> (term.parNode == <span class="hljs-keyword">null</span>) {<br>            <span class="hljs-comment">//删除根节点</span><br>            <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//左子树为空</span><br>                term.data = term.right.data;<br>                <span class="hljs-comment">//根节点的 左树的 左节点，左树的 右节点</span><br>                Tree rLOfTerm = term.right.left, rROfTerm = term.right.right;<br>                <span class="hljs-comment">//换子节点</span><br>                term.right = rROfTerm;<br>                term.left = rLOfTerm;<br>                <span class="hljs-comment">//换父节点</span><br>                <span class="hljs-keyword">if</span> (rLOfTerm != <span class="hljs-keyword">null</span>) {<br>                    rLOfTerm.parNode = term;<br>                }<br>                <span class="hljs-keyword">if</span> (rROfTerm != <span class="hljs-keyword">null</span>) {<br>                    rROfTerm.parNode = term;<br>                }           <br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-comment">//右子树为空,或两子树都在。</span><br>                <span class="hljs-comment">//根节点的 左树的 左节点，左树的 右节点</span><br>                Tree lLOfTerm = term.left.left, lROfTerm = term.left.right;<br>                <span class="hljs-comment">//换子节点</span><br>                term.data = term.left.data;<br>                term.left = lLOfTerm;<br>                Tree deleteNodeTermRight = term.right;<br>                term.right = lROfTerm;<br>                <span class="hljs-keyword">if</span> (deleteNodeTermRight != <span class="hljs-keyword">null</span>) {<br>                    insertNode(term, deleteNodeTermRight);<br>                }<br>                <span class="hljs-keyword">if</span> (lLOfTerm != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//左子树的左枝不为空。</span><br>                    lLOfTerm.parNode = term;<br>                }<br>                <span class="hljs-keyword">if</span> (lROfTerm != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//左子树的右枝不为空。</span><br>                    lROfTerm.parNode = term;<br>                }<br>            }<br>        } <span class="hljs-keyword">else</span> {<br>            <span class="hljs-comment">//删除非根节点。</span><br>            <span class="hljs-comment">//定位节点 父节点 左 右子树</span><br>            Tree parOfTerm = term.parNode, lNode = term.left, rNode = term.right;<br>            <span class="hljs-keyword">if</span> (term.left == <span class="hljs-keyword">null</span>) {<br>                <span class="hljs-comment">//删除节点左子树为空。</span><br>                <span class="hljs-comment">//换父节点</span><br>                rNode.parNode = parOfTerm;<br>                <span class="hljs-keyword">if</span> (parOfTerm.left == term) {<br>                    parOfTerm.left = rNode;<br>                } <span class="hljs-keyword">else</span> {<br>                    parOfTerm.right = rNode;<br>                }<br>            } <span class="hljs-keyword">else</span> {<br>                <span class="hljs-comment">//删除节点左子树为空，或两子树都在</span><br>                <span class="hljs-comment">//换父节点</span><br>                lNode.parNode = term.parNode;<br>                <span class="hljs-comment">//换子节点</span><br>                <span class="hljs-keyword">if</span> (parOfTerm.left == term) {<br>                    <span class="hljs-comment">//当前节点为父节点左枝，赋值</span><br>                    parOfTerm.left = lNode;<br>                } <span class="hljs-keyword">else</span> {<br>                    <span class="hljs-comment">//...</span><br>                    parOfTerm.right = lNode;<br>                }<br>                <span class="hljs-keyword">if</span> (term.right != <span class="hljs-keyword">null</span>) {<br>                    <span class="hljs-comment">//将 右枝 根节点 插入到左枝中--子节点连带过去。</span><br>                    insertNode(term.left, term.right);<br>                }<br>            }<br>        }<br>    }<br><br>    System.out.println(String.format(<span class="hljs-string">"删除%3d,"</span>, value));<br>    <span class="hljs-comment">//删除后的所有元素</span><br>    List&lt;Object&gt; newNodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    traverseTree(father, newNodeData, traverseOrder.DLR);<br><br>    System.out.print(<span class="hljs-string">"\t删除元素: "</span>);<br>    <span class="hljs-comment">//原树的补集</span><br>    Object[] arr3 = nodeData.stream().filter(elem -&gt; !newNodeData.contains(elem)).toArray();<br>    <span class="hljs-keyword">for</span> (Object o : arr3) {<br>        <span class="hljs-comment">//遍历输出</span><br>        System.out.print(o + <span class="hljs-string">" "</span>);<br>    }<br>    System.out.println();<br>}<br></code></pre></td></tr></tbody></table></figure>



<h5 id="2-2-8-2-删除子树"><a href="#2-2-8-2-删除子树" class="headerlink" title="2.2.8.2 删除子树"></a>2.2.8.2 删除子树</h5><p>较上一个更简单，直接使定位到的节点的各值为空节点即可。</p>
<figure class="highlight java"><table><tbody><tr><td class="code"><pre class=" language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点的子树</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTree</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{   <br>    Tree term = findNode(father, value);<br>    <span class="hljs-keyword">if</span>(term!=<span class="hljs-keyword">null</span>){<br>        <span class="hljs-comment">//未删除时根元素的全部元素</span><br>	    List&lt;Object&gt; nodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    	traverseTree(father, nodeData, traverseOrder.LDR);<br>        <span class="hljs-comment">//存在此子树</span><br>        term.left = <span class="hljs-keyword">null</span>;<br>        term.right = <span class="hljs-keyword">null</span>;<br>        term.data = -<span class="hljs-number">1</span>;<br>        System.out.print(String.format(<span class="hljs-string">"删除%3d 为根节点的树,"</span>, value));<br>        <span class="hljs-comment">//删除后的所有元素</span><br>        List&lt;Object&gt; newNodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        traverseTree(father, newNodeData, traverseOrder.DLR);<br>        System.out.print(<span class="hljs-string">"删除的子树节点: "</span>);<br>        <span class="hljs-comment">//原树的补集</span><br>        Object[] arr3 = nodeData.stream().filter(elem -&gt; !newNodeData.contains(elem)).toArray();<br>        <span class="hljs-keyword">for</span> (Object o : arr3) {<br>            <span class="hljs-comment">//遍历输出</span><br>            System.out.print(o + <span class="hljs-string">" "</span>);<br>        }<br>        System.out.println();<br><br>    }<span class="hljs-keyword">else</span>{<br>        System.out.println(String.format(<span class="hljs-string"><code class="language-hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> father 操作的树</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> value  根据值删除第一次出现的节点的子树</span><br><span class="hljs-comment">*/</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTree</span><span class="hljs-params">(Tree father, <span class="hljs-keyword">int</span> value)</span> </span>{   <br>    Tree term = findNode(father, value);<br>    <span class="hljs-keyword">if</span>(term!=<span class="hljs-keyword">null</span>){<br>        <span class="hljs-comment">//未删除时根元素的全部元素</span><br>	    List&lt;Object&gt; nodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    	traverseTree(father, nodeData, traverseOrder.LDR);<br>        <span class="hljs-comment">//存在此子树</span><br>        term.left = <span class="hljs-keyword">null</span>;<br>        term.right = <span class="hljs-keyword">null</span>;<br>        term.data = -<span class="hljs-number">1</span>;<br>        System.out.print(String.format(<span class="hljs-string">"删除%3d 为根节点的树,"</span>, value));<br>        <span class="hljs-comment">//删除后的所有元素</span><br>        List&lt;Object&gt; newNodeData = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        traverseTree(father, newNodeData, traverseOrder.DLR);<br>        System.out.print(<span class="hljs-string">"删除的子树节点: "</span>);<br>        <span class="hljs-comment">//原树的补集</span><br>        Object[] arr3 = nodeData.stream().filter(elem -&gt; !newNodeData.contains(elem)).toArray();<br>        <span class="hljs-keyword">for</span> (Object o : arr3) {<br>            <span class="hljs-comment">//遍历输出</span><br>            System.out.print(o + <span class="hljs-string">" "</span>);<br>        }<br>        System.out.println();<br><br>    }<span class="hljs-keyword">else</span>{<br>        System.out.println(String.format(<span class="hljs-string">"未找到子树:%3d"</span>, value));<br>    }<br>}<br></code></pre></td></tr></tbody></table></figure>




                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">张小白</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://blogofxyz.top/2022/02/10/%E9%A1%BA%E5%BA%8F%E4%BA%8C%E5%8F%89%E6%A0%91/">https://blogofxyz.top/2022/02/10/%E9%A1%BA%E5%BA%8F%E4%BA%8C%E5%8F%89%E6%A0%91/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">张小白</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                                <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">
                                    <span class="chip bg-color">数据结构</span>
                                </a>
                            
                                <a href="/tags/%E6%A0%91/">
                                    <span class="chip bg-color">树</span>
                                </a>
                            
                                <a href="/tags/Tree/">
                                    <span class="chip bg-color">Tree</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    
    <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid="></script>
    <div class="addthis_inline_share_toolbox"></div>
    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.JPG") 100% 100% no-repeat;
	    color: white;
    opacity: 0.8;
    font-size: 18px;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
	text-indent:2rem;
        display: list-item;
        line-height: 2.2rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
	.v[data-class="v"] .vwrap .vheader .vinput {
		width: 32%;
		border-bottom: 1px dashed #dedede;
	}
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
	let metaPlaceholder = {"nick":"昵称/QQ号(必填)","mail":"邮箱(必填)","link":"网址(https://)"} ;
	
	new Valine({
			el: '#vcomments',
			appId: 'ghConjcbp7CpCRHJFPIRDdd2-gzGzoHsz',
			appKey: 'XnhsRQe0DKrPj7X8NnqYg6BX',
			notify: 'true' === 'true',
			verify: 'true' === 'true',
			visitor: 'true' === 'true',
			avatar: 'identicon',
			pageSize: '10',
			lang: 'zh-CN',
			placeholder: '有事不怕打扰，如果较急，可使用右侧反馈快速接受。',
			meta: ["y-nick", "e-mail", "your-link"],
			recordIP: 'true' === 'true',
			enableQQ: 'identicon',
			requiredFields: ["721850218d5dfa3e2ad5b3ac5a69dad8"],
			master: ["721850218d5dfa3e2ad5b3ac5a69dad8"],
			friends: ["4802978b7156ffcf24b571b35c594ad7"],
			tagMeta: ["发文地", "认识地", "过路地"],
			metaPlaceholder: metaPlaceholder,
		});
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2022/02/23/hexo%E7%94%9F%E6%88%90%E6%96%87%E7%AB%A0/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="hexo生成文章">
                        
                        <span class="card-title">hexo生成文章</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Hexo命令行新建文章的用法与区别
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2022-02-23
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Hexo/" class="post-category">
                                    Hexo
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Hexo/">
                        <span class="chip bg-color">Hexo</span>
                    </a>
                    
                    <a href="/tags/Blog/">
                        <span class="chip bg-color">Blog</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2022/02/05/vue-cli%E8%B5%84%E6%BA%90%E9%97%AE%E9%A2%98/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/15.jpg" class="responsive-img" alt="vue-cli资源问题">
                        
                        <span class="card-title">vue-cli资源问题</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            刚开始时遇到的Vue-cli中资源使用与路径问题。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2022-02-05
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Vue/" class="post-category">
                                    Vue
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Vue/">
                        <span class="chip bg-color">Vue</span>
                    </a>
                    
                    <a href="/tags/Vue-cli/">
                        <span class="chip bg-color">Vue-cli</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: X-Y-Z`s Blog<br />'
            + '文章作者: Zhang-little-white<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1,h2, h3, h4, h5'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1,h2, h3, h4, h5').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2022</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">Zhang-little-white</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">53.2k</span>
            
            
            
            
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "8";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }
                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp">
				<img src="/medias/icp.png"豫ICP备2021025736号
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">豫ICP备2021025736号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/xiaohuixian" class="tooltipped" target="_blank" data-tooltip="visit my GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1970476603@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1970476603" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1970476603" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
				
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>
<div>
<a onclick="switchNightMode()" id="sma" title="模式切换">
    <i class="fa fa-moon-o" id="nightMode" aria-hidden="true"></i>
</a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/libs/mermaid/mermaid.min.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b3593488200a34a873defcaa11fc888a";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;" ID="tuxiaochao">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/348756"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	<script type="text/javascript">
//	//只在桌面版网页启用特效
	//var windowWidth = $(window).width();
	//if (windowWidth > 768) {
//		document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
//	}
	</script>
	
	<script type="text/javascript">
		var OriginTitile=document.title,st;
		document.addEventListener("visibilitychange",function(){ document.hidden?(document.title="ヽ(●-`Д´-)ノ110，有人失踪了",clearTimeout(st)):(document.title="(Ő∀Ő3)ノ失踪人口回归！",st=setTimeout(function(){document.title=OriginTitile},3e3))
		})
	</script>


</body>

</html>
